package com.cyzy.controller;

import com.cyzy.dto.Result;
import com.cyzy.pojo.Course;
import com.cyzy.pojo.Seckill;

import com.cyzy.pojo.SeckillStudent;
import com.cyzy.service.SecKillService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/seckill")
public class SecKillController {

    @Autowired
    private SecKillService secKillService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    /**
     * @description: 查询所有的秒杀活动
     * @author: yangJingShi
     * @date: 2025/5/29 上午11:23
     * @param: []
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/getAllSecKill")
    public Result getAllSecKill(){
        List<Seckill> allSecKill = secKillService.getAllSecKill();
        return Result.ok().data("allSecKill",allSecKill);
    }

    /**
     * @description: 通过秒杀ID查询对应的详情
     * @author: yangJingShi
     * @date: 2025/5/29 上午11:25
     * @param: [seckillId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/queryDetailBySeckillId")
    public Result queryDetailBySeckillId(@RequestParam("seckillId") Long seckillId){
        Seckill seckill = secKillService.queryDetailBySeckillId(seckillId);
        return Result.ok().data("secKillDetail",seckill);
    }

    /**
     * @description: 通过秒杀课程的课程来查询课程的详情
     * @author: yangJingShi
     * @date: 2025/5/29 下午10:21
     * @param: [courseId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/queryCourseById")
    public Result queryCourseById(@RequestParam("courseId") Long courseId){
        Course course = secKillService.queryCourseById(courseId);
        return Result.ok().data("course",course);
    }

    /**
     * @description: 检测用户实名状态
     * @author: yangJingShi
     * @date: 2025/5/30 下午2:20
     * @param: [studentId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/queryStuAuthen")
    public Result queryStuAuthen(@RequestParam("studentId") Long studentId){
        System.out.println(studentId);
        Boolean stuAuthen = secKillService.queryStuAuthen(studentId);
        return Result.ok().data("isAuthenticated",stuAuthen);
    }

    /**
     * @description: 查询redis里面剩余的库存
     * @author: yangJingShi
     * @date: 2025/5/30 下午2:22
     * @param: [seckillId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/querySeckillNum")
    public Result querySeckillNum(@RequestParam("seckillId") Long seckillId){
        System.out.println(seckillId);
        String key="seckill"+seckillId;
        Long len = redisTemplate.opsForSet().size(key);
        System.out.println("剩余的秒杀课程数量"+len);
        return Result.ok().data("number",len);
    }

    /**
     * @description: 用户确定秒杀
     * @author: yangJingShi
     * @date: 2025/6/5 上午9:20
     * @param: [seckillId, studentId, courseId, orderAmount]
     * @return: com.cyzy.dto.Result
     **/
    @PostMapping("/secKillCourse")
    public Result secKillCourse(@RequestBody SeckillStudent secStu){

        System.out.println(secStu);

        String queryId = UUID.randomUUID().toString();

        Map<String, Object> map = new HashMap<>();
        map.put("studentId",secStu.getStudentId());
        map.put("seckillId",secStu.getSeckillId());
        //查询该账号是否已经购买过了
        map.put("courseId",secStu.getCourseId());
        map.put("orderAmount",secStu.getOrderAmount());
        map.put("queryId", queryId);

        rocketMQTemplate.convertAndSend("seckill-topic",map);

        // 预存储初始状态（处理中）
        redisTemplate.opsForValue().set(
                "seckill:result:" + queryId,
                Result.ok().code(202).message("处理中"),
                10,
                TimeUnit.MINUTES
        );
        return Result.ok().message("秒杀请求已受理").data("queryId", queryId);

    }

    /**
     * @description: 查询秒杀的结果
     * @author: yangJingShi
     * @date: 2025/6/5 上午9:40
     * @param: [queryId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/querySecKillResult")
    public Result querySecKillResult(@RequestParam("queryId") String queryId) {
        String redisKey = "seckill:result:" + queryId;
        Result result = (Result) redisTemplate.opsForValue().get(redisKey);

        if (result != null) {
            // 只返回一次结果，查询后删除
            redisTemplate.delete(redisKey);
            return result;
        } else {
            return Result.error().message("查询ID不存在或已过期");
        }
    }

    /**
     * @description: 查询用户的限购情况
     * @author: yangJingShi
     * @date: 2025/6/5 上午9:41
     * @param: [studentId, seckillId, limitCount]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/studentLimit")
    public Result studentLimit(@RequestParam("studentId") Long studentId,@RequestParam("seckillId") Long seckillId,
                               @RequestParam("limitCount") Long limitCount){
        System.out.println("studentId的值："+studentId);
        System.out.println("seckillId的值："+seckillId);
        System.out.println("limitCount的值："+limitCount);
        boolean b = secKillService.queryUserLimit(studentId, seckillId, limitCount);
        if (b){
            System.out.println("用户限购");
        }else{
            System.out.println("用户不限购");
        }
        return Result.ok().message("查询用户限购情况").data("isLimit",b);
    }

}
